package app.modules.infrastructure.lov.facade;

import app.modules.infrastructure.lov.persistence.dao.ValueItemDAO;
import app.modules.infrastructure.lov.persistence.entity.ValueItemEO;
import jasmine.framework.common.util.CollectionUtil;
import jasmine.framework.common.util.NewUtil;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author mh.z
 */
@Component
public class LovFacadeImpl implements LovFacade {
    private ValueItemDAO valueItemDAO;

    public LovFacadeImpl(ValueItemDAO valueItemDAO) {
        this.valueItemDAO = valueItemDAO;
    }

    @Override
    public boolean checkItemValue(String valueSetGlobalCode, String valueCode) {
        return checkItemValues(valueSetGlobalCode, Collections.singletonList(valueCode));
    }

    @Override
    public boolean checkItemValues(String valueSetGlobalCode, Collection<String> valueCodes) {
        List<ValueItemEO> list = valueItemDAO.listByValueSetGlobalCodeNoI18n(valueSetGlobalCode, valueCodes);

        return (list.size() >= valueCodes.size());
    }

    @Override
    public String queryItemName(String valueSetGlobalCode, String valueCode) {
        List<ValueItemEO> list = valueItemDAO.listByValueSetGlobalCode(valueSetGlobalCode,
                Collections.singletonList(valueCode));

        if (CollectionUtil.isEmpty(list)) {
            return null;
        }

        ValueItemEO valueItemEO = CollectionUtil.getFirst(list);
        String itemName = valueItemEO.getValueName();

        return itemName;
    }

    @Override
    public Map<String, String> queryItemNames(String valueSetGlobalCode, Collection<String> valueCodes) {
        List<ValueItemEO> list = valueItemDAO.listByValueSetGlobalCode(valueSetGlobalCode, valueCodes);

        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyMap();
        }

        Map<String, String> map = NewUtil.map(list.size());
        list.forEach(item -> {
            map.put(item.getValueCode(), item.getValueName());
        });

        return map;
    }

}
